<?php if(!defined('BASEPATH')) exit("Sorry, what you're looking not found.");
class C_lomba extends Nvl_Controller{
    function __construct(){
        parent::__construct();
        session_start();
		$this->__checkSession();
        $this->load->model('m_lomba');
    }

    function index(){
        $this->load->view('pages/v_lomba');
    }

    function get_list(){
        $pagenum = $this->input->get('pagenum');
        $pagesize = $this->input->get('pagesize');
		$start = $pagenum * $pagesize;
		$end = $start + $pagesize;
		$search_text = $this->input->get('search_text');
		$result = $this->m_lomba->get_list($start, $end, $search_text);
		echo $result;
    }
	
	function save(){
		$params = json_decode($this->input->post("params"));
		$form_data = $params->form_data;
		$this->db->trans_start();
		$sql = "SELECT MAX(lomba_kode) AS max FROM t_lomba where DATE_FORMAT(lomba_tanggal,'%Y') = ". date('Y');
		$query = $this->db->query($sql);
		$lomba_kode = $query->row()->max;
		$lomba_kode = $lomba_kode == '' ? date('Y') . '001' : (int)substr($lomba_kode,0,4) . str_pad(((int)substr($lomba_kode,4,3) + 1), 3, '0', STR_PAD_LEFT);
		$data = array(
			"lomba_sekolah_id"=>$_SESSION[SESSION_SCHOOLID],
			"lomba_kode"=>$lomba_kode,
			"lomba_judul"=>$form_data->lomba_judul,
			"lomba_tanggal"=>date('Y-m-d', strtotime($form_data->lomba_tanggal)),
			"lomba_deskripsi"=>$form_data->lomba_deskripsi,
			"lomba_cp"=>$form_data->lomba_cp,
			"lomba_cp_no"=>$form_data->lomba_cp_no,
			"lomba_tahunajar"=>$form_data->lomba_tahunajar,
			"lomba_semester"=>$form_data->lomba_semester,
			"lomba_level_id"=>$form_data->lomba_level_id
		);
		$result = $this->m_lomba->__save($data, (is_numeric($params->lomba_id) ? $params->lomba_id : 0));
		$this->db->trans_complete();
		echo $lomba_kode;
	}
	
	function delete(){
		$lomba_id = $this->input->numeric('lomba_id');
		$result = $this->m_lomba->__deactivate($lomba_id);
		echo $result;
	}
	
	function upload_poster(){
		error_reporting(E_ALL | E_STRICT);
		$filename = $_REQUEST['filename'];
        $this->load->library("UploadHandler", array('filename'=> $filename));
	}
	
	function update_poster_lomba(){
		$lomba_poster = $this->input->post('params');
		$lomba_kode = explode('.', $lomba_poster);
		$lomba_kode = $lomba_kode[0];
		$this->db->where('lomba_kode', $lomba_kode)->update('t_lomba', array('lomba_poster'=>$lomba_poster));
	}
}